package Servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet(urlPatterns = { "/admin/servlet" })
public class Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private final int WIDTH = 100;  
    private final int HEIGTH = 25;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		BufferedImage img = new BufferedImage(WIDTH, HEIGTH, BufferedImage.TYPE_INT_RGB);
		Graphics g = img.getGraphics();
		g.setColor(Color.white);
		g.fillRect(0, 0, WIDTH, HEIGTH);
		g.setColor(Color.black);
		Random rnd = new Random();
		for(int i=0;i<10;i++)
		{
			int x1 = rnd.nextInt(WIDTH);
			int y1 = rnd.nextInt(HEIGTH);
			int x2 = rnd.nextInt(WIDTH);
			int y2 = rnd.nextInt(HEIGTH);
			g.drawLine(x1, y1, x2, y2);
		}
		g.setFont(new Font("宋体",Font.BOLD,20));
		g.setColor(Color.RED);
		String num = ShowNumber(4);
        request.getSession().setAttribute("code",num);
		g.drawString(num, 40, 15);
		g.dispose();
		ServletOutputStream sos = response.getOutputStream();
		ImageIO.write(img, "jpeg", sos);
		sos.flush();
		sos.close();
		
	}
	private String ShowNumber(int size)
	{
		String str = "23456789abcdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
		StringBuffer buf = new StringBuffer();
		Random r = new Random();
		for(int i=0;i<size;i++)
		{
			int pos = r.nextInt(str.length());
			buf.append(str.substring(pos, pos+1));
		}
		return buf.toString();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
